package com.benefm.multipar.pad.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.benefm.multipar.pad.R;

import java.util.Random;

public class DoubleRingDashboard extends View {


    // 外环参数
    private Paint outerRingPaint, outerScalePaint, outerValuePaint;
    private float outerValue = 82.0f;
    private float outerMax = 100.0f;
    private float outerStartAngle = 135f;
    private float outerSweepAngle = 270f;
    private int outerNormalColor = Color.parseColor("#29B6F6"); // 蓝色
    private int outerWarningColor = Color.parseColor("#F44336"); // 红色
    private int outerCritical = 85; // 外环警告阈值
    private String outerTitle = "OXYGEN";
    private String outerUnit = "%";

    // 内环参数
    private Paint innerRingPaint, innerScalePaint, innerValuePaint;
    private float innerValue = 120.0f;
    private float innerMax = 200.0f;
    private float innerStartAngle = 135f;
    private float innerSweepAngle = 270f;
    private int innerNormalColor = Color.parseColor("#7E57C2"); // 紫色
    private int innerWarningColor = Color.parseColor("#FF9800"); // 橙色
    private int innerCritical = 160; // 内环警告阈值
    private String innerTitle = "PULSE";
    private String innerUnit = "BPM";

    // 共享元素
    private Paint heartPaint, wavePaint, textPaint, valuePaint;
    private Path heartPath, wavePath;
    private RectF outerRingRect, innerRingRect;
    private int width, height;
    private float centerX, centerY;
    private float radius;
    private Random random = new Random();

    public DoubleRingDashboard(Context context) {
        super(context);
        init(null);
    }

    public DoubleRingDashboard(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        // 解析自定义属性
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DoubleRingDashboard);
            // 外环属性
            outerNormalColor = a.getColor(R.styleable.DoubleRingDashboard_outerNormalColor, outerNormalColor);
            outerWarningColor = a.getColor(R.styleable.DoubleRingDashboard_outerWarningColor, outerWarningColor);
            outerCritical = a.getInt(R.styleable.DoubleRingDashboard_outerCritical, outerCritical);
            outerTitle = a.getString(R.styleable.DoubleRingDashboard_outerTitle);
            if (outerTitle == null) outerTitle = "OXYGEN";
            outerUnit = a.getString(R.styleable.DoubleRingDashboard_outerUnit);
            if (outerUnit == null) outerUnit = "%";

            // 内环属性
            innerNormalColor = a.getColor(R.styleable.DoubleRingDashboard_innerNormalColor, innerNormalColor);
            innerWarningColor = a.getColor(R.styleable.DoubleRingDashboard_innerWarningColor, innerWarningColor);
            innerCritical = a.getInt(R.styleable.DoubleRingDashboard_innerCritical, innerCritical);
            innerTitle = a.getString(R.styleable.DoubleRingDashboard_innerTitle);
            if (innerTitle == null) innerTitle = "PULSE";
            innerUnit = a.getString(R.styleable.DoubleRingDashboard_innerUnit);
            if (innerUnit == null) innerUnit = "BPM";

            a.recycle();
        }

        // 外环画笔
        outerRingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        outerRingPaint.setStyle(Paint.Style.STROKE);
        outerRingPaint.setStrokeWidth(18f);
        outerRingPaint.setStrokeCap(Paint.Cap.ROUND);

        // 外环刻度画笔
        outerScalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        outerScalePaint.setStrokeWidth(4f);
        outerScalePaint.setColor(Color.WHITE);
        outerScalePaint.setStrokeCap(Paint.Cap.ROUND);

        // 外环数值画笔
        outerValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        outerValuePaint.setTextSize(22f);
        outerValuePaint.setColor(Color.parseColor("#B0BEC5"));
        outerValuePaint.setTextAlign(Paint.Align.CENTER);

        // 内环画笔
        innerRingPaint = new Paint(outerRingPaint);
        innerRingPaint.setStrokeWidth(14f);

        // 内环刻度画笔
        innerScalePaint = new Paint(outerScalePaint);
        innerScalePaint.setStrokeWidth(3f);

        // 内环数值画笔
        innerValuePaint = new Paint(outerValuePaint);
        innerValuePaint.setTextSize(18f);

        // 心形图标画笔
        heartPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        heartPaint.setStyle(Paint.Style.FILL);
        heartPaint.setColor(outerWarningColor);

        // 心电图画笔
        wavePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        wavePaint.setStyle(Paint.Style.STROKE);
        wavePaint.setStrokeWidth(4f);
        wavePaint.setColor(Color.WHITE);

        // 主文本画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(24f);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 主数值画笔
        valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        valuePaint.setTextSize(56f);
        valuePaint.setColor(Color.WHITE);
        valuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        valuePaint.setTextAlign(Paint.Align.CENTER);

        heartPath = new Path();
        wavePath = new Path();
        outerRingRect = new RectF();
        innerRingRect = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        radius = Math.min(width, height) * 0.4f;
        centerX = width / 2f;
        centerY = height / 2f;

        // 外环区域
        float outerRadius = radius * 1.0f;
        outerRingRect.set(
                centerX - outerRadius,
                centerY - outerRadius,
                centerX + outerRadius,
                centerY + outerRadius
        );

        // 内环区域
        float innerRadius = radius * 0.7f;
        innerRingRect.set(
                centerX - innerRadius,
                centerY - innerRadius,
                centerX + innerRadius,
                centerY + innerRadius
        );

        // 构建心形路径
        buildHeartPath();

        // 构建心电图路径
        buildWaveformPath();
    }

    private void buildHeartPath() {
        float heartSize = radius * 0.2f;
        heartPath.reset();

        // 心形绘制
        heartPath.moveTo(centerX, centerY + heartSize * 0.4f);

        // 左侧曲线
        heartPath.cubicTo(
                centerX - heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX - heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX - heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 顶部曲线
        heartPath.cubicTo(
                centerX, centerY - heartSize * 0.9f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 右侧曲线
        heartPath.cubicTo(
                centerX + heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX + heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX, centerY + heartSize * 0.4f
        );

        heartPath.close();
    }

    private void buildWaveformPath() {
        float waveHeight = radius * 0.15f;
        float startX = centerX - radius * 0.15f;
        float startY = centerY;

        wavePath.reset();
        wavePath.moveTo(startX, startY);

        // 绘制心电图波形
        wavePath.lineTo(startX + radius * 0.1f, startY - waveHeight * 0.5f);
        wavePath.lineTo(startX + radius * 0.15f, startY + waveHeight * 0.3f);
        wavePath.lineTo(startX + radius * 0.2f, startY - waveHeight * 0.4f);
        wavePath.lineTo(startX + radius * 0.25f, startY);
        wavePath.lineTo(startX + radius * 0.3f, startY - waveHeight);
        wavePath.lineTo(startX + radius * 0.35f, startY + waveHeight * 0.6f);
        wavePath.lineTo(startX + radius * 0.4f, startY - waveHeight * 0.3f);
        wavePath.lineTo(startX + radius * 0.45f, startY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制外环
        drawOuterRing(canvas);

        // 2. 绘制内环
        drawInnerRing(canvas);

        // 3. 绘制心形图标
        canvas.drawPath(heartPath, heartPaint);

        // 4. 绘制心电图波形
        canvas.drawPath(wavePath, wavePaint);

        // 5. 绘制主数值
        drawCenterValues(canvas);
    }

    private void drawOuterRing(Canvas canvas) {
        // 背景弧
        outerRingPaint.setColor(Color.parseColor("#37474F"));
        canvas.drawArc(outerRingRect, outerStartAngle, outerSweepAngle, false, outerRingPaint);

        // 计算正常区域
        float normalPosition = outerSweepAngle * outerCritical / outerMax;

        // 正常区域（蓝色）
        outerRingPaint.setColor(outerNormalColor);
        canvas.drawArc(outerRingRect, outerStartAngle, normalPosition, false, outerRingPaint);

        // 警告区域（红色）
        float warningStart = outerStartAngle + normalPosition;
        float warningSweep = outerSweepAngle - normalPosition;
        outerRingPaint.setColor(outerWarningColor);
        canvas.drawArc(outerRingRect, warningStart, warningSweep, false, outerRingPaint);

        // 绘制刻度线和数值
        drawOuterScales(canvas);
    }

    private void drawInnerRing(Canvas canvas) {
        // 背景弧
        innerRingPaint.setColor(Color.parseColor("#263238"));
        canvas.drawArc(innerRingRect, innerStartAngle, innerSweepAngle, false, innerRingPaint);

        // 计算正常区域
        float normalPosition = innerSweepAngle * innerCritical / innerMax;

        // 正常区域（紫色）
        innerRingPaint.setColor(innerNormalColor);
        canvas.drawArc(innerRingRect, innerStartAngle, normalPosition, false, innerRingPaint);

        // 警告区域（橙色）
        float warningStart = innerStartAngle + normalPosition;
        float warningSweep = innerSweepAngle - normalPosition;
        innerRingPaint.setColor(innerWarningColor);
        canvas.drawArc(innerRingRect, warningStart, warningSweep, false, innerRingPaint);

        // 绘制刻度线和数值
        drawInnerScales(canvas);
    }

    private void drawOuterScales(Canvas canvas) {
        int majorScales = 5; // 主刻度数量
        float scaleLength = 20f;

        for (int i = 0; i <= majorScales; i++) {
            float value = i * (outerMax / majorScales);
            float angle = outerStartAngle + (outerSweepAngle * i / majorScales);
            float angleRad = (float) Math.toRadians(angle);

            // 计算位置
            float startX = (float) (centerX + radius * Math.cos(angleRad));
            float startY = (float) (centerY + radius * Math.sin(angleRad));
            float endX = (float) (centerX + (radius - scaleLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius - scaleLength) * Math.sin(angleRad));

            // 绘制刻度线
            canvas.drawLine(startX, startY, endX, endY, outerScalePaint);

            // 绘制刻度值
            if (i > 0 && i < majorScales) {
                float textRadius = radius - scaleLength - 20f;
                float textX = (float) (centerX + textRadius * Math.cos(angleRad));
                float textY = (float) (centerY + textRadius * Math.sin(angleRad)) + 12;

                outerValuePaint.setColor(i <= outerCritical/(outerMax/majorScales) ?
                        outerNormalColor : outerWarningColor);
                canvas.drawText(String.valueOf((int) value), textX, textY, outerValuePaint);
            }
        }

        // 绘制小刻度
        int minorScales = majorScales * 4;
        for (int i = 0; i <= minorScales; i++) {
            if (i % 4 == 0) continue; // 跳过主刻度

            float angle = outerStartAngle + (outerSweepAngle * i / minorScales);
            float angleRad = (float) Math.toRadians(angle);

            float minorLength = 10f;
            float startX = (float) (centerX + radius * Math.cos(angleRad));
            float startY = (float) (centerY + radius * Math.sin(angleRad));
            float endX = (float) (centerX + (radius - minorLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius - minorLength) * Math.sin(angleRad));

            canvas.drawLine(startX, startY, endX, endY, outerScalePaint);
        }

        // 绘制外环标题
        float outerTitleAngle = outerStartAngle + outerSweepAngle / 2;
        float outerTitleRad = (float) Math.toRadians(outerTitleAngle);
        float outerTitleRadius = radius + 40f;
        float outerTitleX = (float) (centerX + outerTitleRadius * Math.cos(outerTitleRad));
        float outerTitleY = (float) (centerY + outerTitleRadius * Math.sin(outerTitleRad));

        outerValuePaint.setColor(Color.WHITE);
        outerValuePaint.setTextSize(24f);
        canvas.drawText(outerTitle, outerTitleX, outerTitleY, outerValuePaint);

        // 绘制外环当前值
        float outerValueAngle = outerStartAngle + (outerSweepAngle * outerValue / outerMax);
        float outerValueRad = (float) Math.toRadians(outerValueAngle);
        float outerValueRadius = radius - 20f;
        float outerValueX = (float) (centerX + outerValueRadius * Math.cos(outerValueRad));
        float outerValueY = (float) (centerY + outerValueRadius * Math.sin(outerValueRad));

        outerValuePaint.setColor(outerValue < outerCritical ? outerNormalColor : outerWarningColor);
        outerValuePaint.setTextSize(28f);
        canvas.drawText(String.format("%.0f", outerValue), outerValueX, outerValueY, outerValuePaint);
    }

    private void drawInnerScales(Canvas canvas) {
        int majorScales = 6; // 主刻度数量
        float scaleLength = 15f;

        for (int i = 0; i <= majorScales; i++) {
            float value = i * (innerMax / majorScales);
            float angle = innerStartAngle + (innerSweepAngle * i / majorScales);
            float angleRad = (float) Math.toRadians(angle);

            // 计算位置
            float innerRadius = radius * 0.7f;
            float startX = (float) (centerX + innerRadius * Math.cos(angleRad));
            float startY = (float) (centerY + innerRadius * Math.sin(angleRad));
            float endX = (float) (centerX + (innerRadius - scaleLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (innerRadius - scaleLength) * Math.sin(angleRad));

            // 绘制刻度线
            canvas.drawLine(startX, startY, endX, endY, innerScalePaint);

            // 绘制刻度值
            if (i > 0 && i < majorScales) {
                float textRadius = innerRadius - scaleLength - 15f;
                float textX = (float) (centerX + textRadius * Math.cos(angleRad));
                float textY = (float) (centerY + textRadius * Math.sin(angleRad)) + 10;

                innerValuePaint.setColor(i <= innerCritical/(innerMax/majorScales) ?
                        innerNormalColor : innerWarningColor);
                canvas.drawText(String.valueOf((int) value), textX, textY, innerValuePaint);
            }
        }

        // 绘制内环标题
        float innerTitleAngle = innerStartAngle + innerSweepAngle / 2;
        float innerTitleRad = (float) Math.toRadians(innerTitleAngle);
        float innerTitleRadius = radius * 0.55f;
        float innerTitleX = (float) (centerX + innerTitleRadius * Math.cos(innerTitleRad));
        float innerTitleY = (float) (centerY + innerTitleRadius * Math.sin(innerTitleRad));

        innerValuePaint.setColor(Color.WHITE);
        innerValuePaint.setTextSize(20f);
        canvas.drawText(innerTitle, innerTitleX, innerTitleY, innerValuePaint);

        // 绘制内环当前值
        float innerValueAngle = innerStartAngle + (innerSweepAngle * innerValue / innerMax);
        float innerValueRad = (float) Math.toRadians(innerValueAngle);
        float innerValueRadius = radius * 0.55f;
        float innerValueX = (float) (centerX + innerValueRadius * Math.cos(innerValueRad));
        float innerValueY = (float) (centerY + innerValueRadius * Math.sin(innerValueRad));

        innerValuePaint.setColor(innerValue < innerCritical ? innerNormalColor : innerWarningColor);
        innerValuePaint.setTextSize(24f);
        canvas.drawText(String.format("%.0f", innerValue), innerValueX, innerValueY, innerValuePaint);
    }

    private void drawCenterValues(Canvas canvas) {
        // 绘制外环数值
        float outerTextY = centerY - 30;
        textPaint.setTextSize(26f);
        textPaint.setColor(outerValue < outerCritical ? outerNormalColor : outerWarningColor);
        canvas.drawText(String.format("%.0f%s", outerValue, outerUnit), centerX, outerTextY, textPaint);

        // 绘制内环数值
        float innerTextY = centerY + 40;
        textPaint.setTextSize(24f);
        textPaint.setColor(innerValue < innerCritical ? innerNormalColor : innerWarningColor);
        canvas.drawText(String.format("%.0f%s", innerValue, innerUnit), centerX, innerTextY, textPaint);

        // 绘制标题
        textPaint.setTextSize(20f);
        textPaint.setColor(Color.parseColor("#B0BEC5"));
        canvas.drawText(outerTitle, centerX, centerY - 70, textPaint);
    }

    // 设置外环值（带动画）
    public void setOuterValue(float value, boolean animate) {
        if (value > outerMax) value = outerMax;
        if (value < 0) value = 0;

        if (animate) {
            ValueAnimator animator = ValueAnimator.ofFloat(outerValue, value);
            animator.setDuration(1200);
            animator.setInterpolator(new AccelerateDecelerateInterpolator());
            animator.addUpdateListener(animation -> {
                outerValue = (float) animation.getAnimatedValue();
                invalidate();
            });
            animator.start();
        } else {
            outerValue = value;
            invalidate();
        }
    }

    // 设置内环值（带动画）
    public void setInnerValue(float value, boolean animate) {
        if (value > innerMax) value = innerMax;
        if (value < 0) value = 0;

        if (animate) {
            ValueAnimator animator = ValueAnimator.ofFloat(innerValue, value);
            animator.setDuration(1200);
            animator.setInterpolator(new AccelerateDecelerateInterpolator());
            animator.addUpdateListener(animation -> {
                innerValue = (float) animation.getAnimatedValue();
                invalidate();
            });
            animator.start();
        } else {
            innerValue = value;
            invalidate();
        }
    }

    // 设置外环参数
    public void setOuterParams(String title, String unit, int max, int critical,
                               int normalColor, int warningColor) {
        this.outerTitle = title;
        this.outerUnit = unit;
        this.outerMax = max;
        this.outerCritical = critical;
        this.outerNormalColor = normalColor;
        this.outerWarningColor = warningColor;
        invalidate();
    }

    // 设置内环参数
    public void setInnerParams(String title, String unit, int max, int critical,
                               int normalColor, int warningColor) {
        this.innerTitle = title;
        this.innerUnit = unit;
        this.innerMax = max;
        this.innerCritical = critical;
        this.innerNormalColor = normalColor;
        this.innerWarningColor = warningColor;
        invalidate();
    }

    // 模拟心跳动画效果
    private ValueAnimator heartBeatAnimator;

    public void startHeartBeatAnimation() {
        stopHeartBeatAnimation();

        heartBeatAnimator = ValueAnimator.ofFloat(1.0f, 1.1f, 1.0f);
        heartBeatAnimator.setDuration(600);
        heartBeatAnimator.setRepeatCount(ValueAnimator.INFINITE);
        heartBeatAnimator.addUpdateListener(animation -> {
            float scale = (float) animation.getAnimatedValue();

            // 构建缩放后的心形
            Path scaledPath = new Path();
            Matrix matrix = new Matrix();
            matrix.setScale(scale, scale, centerX, centerY);
            heartPath.transform(matrix, scaledPath);

            heartPath = scaledPath;
            invalidate();
        });
        heartBeatAnimator.start();
    }

    public void stopHeartBeatAnimation() {
        if (heartBeatAnimator != null) {
            heartBeatAnimator.cancel();
            heartBeatAnimator = null;
        }
        // 恢复原始心形
        buildHeartPath();
    }

    // 动态心电图波形动画
    private ValueAnimator waveAnimator;
    private float waveOffset = 0;

    public void startWaveAnimation() {
        stopWaveAnimation();

        waveAnimator = ValueAnimator.ofFloat(0f, 1f);
        waveAnimator.setDuration(2000);
        waveAnimator.setRepeatCount(ValueAnimator.INFINITE);
        waveAnimator.addUpdateListener(animation -> {
            waveOffset = (float) animation.getAnimatedValue();
            updateWaveform();
            invalidate();
        });
        waveAnimator.start();
    }

    private void updateWaveform() {
        float waveHeight = radius * 0.15f;
        float startX = centerX - radius * 0.15f;
        float startY = centerY;

        wavePath.reset();
        wavePath.moveTo(startX, startY);

        // 使用正弦波创建动态波形
        for (int i = 0; i < 8; i++) {
            float x = startX + i * radius * 0.1f;
            float y = startY - (float) (waveHeight * Math.sin((i * 0.8) + waveOffset * 5));
            wavePath.lineTo(x, y);
        }
    }

    public void stopWaveAnimation() {
        if (waveAnimator != null) {
            waveAnimator.cancel();
            waveAnimator = null;
        }
        // 恢复原始心电图
        buildWaveformPath();
    }

}
